package com.thread;

import java.util.concurrent.*;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PrintOutOddEven {
    public static void main(String[] args) {

        OddEven oddEven = new OddEven(2, 39);

        ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 2, 2, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
        for (int i = 0; i < 2; i++) {
            executor.submit(() -> {
                oddEven.print();
            });
        }


    }

}

class OddEven {

    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    int start;
    int end;

    public OddEven(int start, int end) {
        this.start = start;
        this.end = end;
    }

    public void print() {
        lock.lock();
        try {
            while (start <= end) {
                System.out.println(start);
                start++;
                condition.signalAll();
                // 自己阻塞
                condition.await();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

}

